package ee.metadataUtils.impl;

import java.util.HashMap;
import java.util.Map;

import ee.metadataUtils.PropertyMetadata;
import ee.metadataUtils.PropertyMetadataAdapterFactoryRegistry;

/**
 * Caches adapters
 * 
 * @author EECOLOR
 *
 */
public abstract class AbstractPropertyMetadata implements PropertyMetadata {

	private PropertyMetadataAdapterFactoryRegistry _adapterFactoryRegistry;

	private Map<Class<?>, Object> _adapters;
	
	public AbstractPropertyMetadata(PropertyMetadataAdapterFactoryRegistry adapterFactoryRegistry)
	{
		_adapterFactoryRegistry = adapterFactoryRegistry;
		_adapters = new HashMap<Class<?>, Object>();
	}
	
	@Override
	public <T> T getAdapter(Class<T> adapterType) throws AdapterNotFoundException {
		
		if (_adapters.containsKey(adapterType))
		{
			return adapterType.cast(_adapters.get(adapterType));
		} else
		{
			if (_adapterFactoryRegistry.hasAdapterFactory(adapterType))
			{
				T adapter = _adapterFactoryRegistry.getAdapterFactory(adapterType).getAdapter(this);
				
				_adapters.put(adapterType, adapter);
				
				return adapter;
			} else
			{
				throw new AdapterNotFoundException("Could not find adapter to type " + adapterType);
			}
		}
	}
	
}
